<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdateRoleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $role = $this->route('role');
        $roleId = $role instanceof \App\Models\Role ? $role->id : ($this->route('role') ?? $this->route('id'));
        
        return [
            'name' => 'required|string|unique:roles,name,' . $roleId,
            'code' => 'required|string|unique:roles,code,' . $roleId,
            'status' => 'required|integer|in:' . implode(',', [
                \App\Models\Role::STATUS_DISABLED,
                \App\Models\Role::STATUS_ENABLED,
            ]),
            'sort' => 'nullable|integer',
            'menu_ids' => 'nullable|array',
            'menu_ids.*' => 'exists:menus,id',
            'permission_ids' => 'nullable|array',
            'permission_ids.*' => 'exists:permissions,id',
            'remark' => 'nullable|string',
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'name.required' => '角色名称不能为空',
            'name.unique' => '角色名称已存在',
            'code.required' => '角色编码不能为空',
            'code.unique' => '角色编码已存在',
            'status.required' => '状态不能为空',
            'status.in' => '状态值不正确',
            'menu_ids.*.exists' => '菜单不存在',
            'permission_ids.*.exists' => '权限不存在',
        ];
    }
}

